#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Author:Lijiacai
Email:1050518702@qq.com
===========================================
CopyRight@JackLee.com
===========================================
"""
import json

import graphene
import base64
import cv2
import numpy as np
from common.view import BaseApi
# from resource.lijiacai.utils.license_plate_recognizer import pipline
from resource.lijiacai.utils import tool

model_path = {
    "plate_type": "./model/plate_type.h5",
    "fontC": "./Font/platech.ttf",
    "watch_cascade": "./model/cascade.xml",
    "model12": "./model/model12.h5",
    "ocr_model": "./model/ocr_plate_all_w_rnn_2.h5"
}
tool.load_models(model_path=model_path)


class LicenseRecognizer(BaseApi):
    name = "LicenseRecognizer"
    description = "车牌识别"

    class Argument:
        base64Image = graphene.String(description="base64的图片")
        imageUrl = graphene.String(description="base64的地址")

    class Return:
        class SearchList1(graphene.ObjectType):
            plateType = graphene.String(description="车牌类型")
            licensePlate = graphene.String(description="识别车牌结果")
            confidence = graphene.String(description="结果置信度")

        rows = graphene.List(SearchList1, description="结果列表")

    def validate_privilege(self, token_info, **kwargs):
        pass

    def deal(self, token_info, prilivege_info, **kwargs):
        base64Image = self.arguments.get("condition", {}).get("base64Image")
        imageUrl = self.arguments.get("condition", {}).get("imageUrl")
        r = tool.Recognizer()
        res = r.predict(image_base64=base64Image, image_url=imageUrl)
        res_ocr = r.ocr_predict(image_base64=base64Image, image_url=imageUrl)
        rows = []
        for i in res:
            if i.get("confidence") > 0.1 and len(i.get("licensePlate")) >= 7:
                if i.get("licensePlate") == 8:
                    i["plateType"] = "新能源车牌"
                if i.get("licensePlate") in res_ocr:
                    res_ocr.remove(i.get("licensePlate"))
                rows.append(i)
        for i in res_ocr:
            if len(i) == 8:
                rows.append({"plateType": "新能源车牌", "licensePlate": i, "confidence": "0.5"})
            else:
                rows.append({"plateType": "未知", "licensePlate": i, "confidence": "0.5"})
        if imageUrl:
            with open("./info.log", "a") as f:
                f.write(json.dumps({"imageUrl": imageUrl, "result": rows}, ensure_ascii=False) + "\n")

        return {"rows": rows}

# class LicenseRecognizer(BaseApi):
#     name = "LicenseRecognizer"
#     description = "车牌识别"
#
#     class Argument:
#         base64Image = graphene.String(description="base64的图片", required=True)
#
#     class Return:
#         class SearchList1(graphene.ObjectType):
#             plateType = graphene.String(description="车牌类型")
#             licensePlate = graphene.String(description="识别车牌结果")
#             confidence = graphene.String(description="结果置信度")
#
#         rows = graphene.List(SearchList1, description="结果列表")
#
#     def validate_privilege(self, token_info, **kwargs):
#         pass
#
#     def deal(self, token_info, prilivege_info, **kwargs):
#         images = self.arguments.get("condition", {}).get("base64Image").split("base64,")
#         imgData = base64.b64decode(images[1])
#         nparr = np.fromstring(imgData, np.uint8)
#         image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
#         se = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3), (-1, -1))
#         image = cv2.morphologyEx(image, cv2.MORPH_CLOSE, se)
#         recognazier = pipline.Recognazier()
#         res = recognazier.direct_recognize(image)
#         rows = []
#         for i in res:
#             if i.get("confidence") > 0.1 and len(i.get("licensePlate")) >= 7:
#                 if i.get("licensePlate") == 8:
#                     i["plateType"] = "新能源车牌"
#                 rows.append(i)
#
#         return {"rows": rows}
